package com.rdc.jiajiadictionary.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.rdc.jiajiadictionary.R;
import com.rdc.jiajiadictionary.bean.Word;

import java.util.List;

public class HistoryAdapter extends RecyclerView.Adapter<HistoryAdapter.ViewHolder> {

    private List<Word> words;
    private OnItemClickListener onItemClickListener;

    /**
     * 子项点击回调接口
     */
    public interface OnItemClickListener{
        void onItemClick(View view,int position);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener){
        this.onItemClickListener = onItemClickListener;
    }

    public HistoryAdapter(List<Word> words){
        this.words = words;
    }

    /**
     * 创建ViewHolder类
     */
    public class ViewHolder extends RecyclerView.ViewHolder{
        TextView nameTv;
        TextView partTv;
        LinearLayout historyItem;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            nameTv = (TextView) itemView.findViewById(R.id.tv_name);
            partTv = (TextView) itemView.findViewById(R.id.tv_part);
            historyItem = (LinearLayout) itemView.findViewById(R.id.ll_history_item);
        }
    }


    /**
     * 加载子项的布局，创建viewHolder对象
     * @param parent
     * @param viewType
     * @return
     */
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.history_recycle_item,parent,false);
        final ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    /**
     * 通过viewHolder加载子项数据，同时设置监听回调接口
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Word word = words.get(position);
        holder.nameTv.setText(word.getWord_name());
        holder.partTv.setText(word.getPart());
        if (onItemClickListener != null){
            holder.historyItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onItemClickListener.onItemClick(v,position);
                }
            });
        }


    }


    @Override
    public int getItemCount() {
        return words.size();
    }
}
